const Service = require("egg").Service;
const crypto = require("crypto");
class UserService extends Service {
  // 查找用户
  async findByPhone(phone) {
    const { app } = this;
    const user = await app.model.User.findOne({
      where: {
        phone
      }
    });
    return user;
  }

  // 创建用户
  async createUser(phone, password) {
    const { app } = this;
    const user = await app.model.User.create({
      phone,
      password
    });
    return user;
  }

  // 验证密码
  async validatePassword(password, hash_password) {
    // 先对需要验证的密码进行加密
    const hash = crypto.createHash("md5", this.app.config.crypto.secret);
    hash.update(password);
    password = hash.digest("hex");
    let res = password === hash_password;
    if (!res) {
      this.ctx.throw(400, "密码错误");
    }
    return true;
  }

  // 生成token
  async generateToken(val) {
    const { app } = this;
    return app.jwt.sign(val, app.config.jwt.secret, {
      expiresIn: app.config.jwt.sign.expiresIn
    });
  }

  // 验证token
  async verifyToken(token) {
    const { app } = this;
    return app.jwt.verify(token, app.config.jwt.secret);
  }

  // 模糊查询遍历用户信息
  async findByUsernameAndPhone(username, phone) {
    const { ctx, app } = this;
    const { Op } = app.Sequelize;
    let pageBean = ctx.query.pageBean;
    // 数据查询
    const where = {};
    if (username !== undefined) {
      where.username = {
        [Op.like]: `%${username}%`
      };
    }
    if (phone !== undefined) {
      where.phone = {
        [Op.like]: `%${phone}%`
      };
    }
    const userList = await app.model.User.findAndCountAll({
      where,
      include: [
        {
          model: app.model.Role,
          required: true,
          attributes: ["rolename"]
        },
        {
          model: app.model.Member
        }
      ],
      offset: pageBean
        ? (pageBean.pageIndex - 1) * pageBean.pageSize
        : undefined,
      limit: pageBean ? parseInt(pageBean.pageSize) : undefined
    });
    return userList;
  }

  // 编辑当前用户信息
  async editCurrentUser(data) {
    const { app, ctx } = this;
    const id = ctx.tokenUser.id;
    const user = await app.model.User.findByPk(id);
    const editUser = await user.update(data);
    return editUser;
  }

  // 注销当前登录用户
  async logoutCurrentUser() {
    const { app, ctx } = this;
    const id = ctx.tokenUser.id;
    const user = await app.model.User.findByPk(id);
    const res = await user.destroy();
    return res;
  }
}

module.exports = UserService;
